#!/usr/bin/env python

# -*- coding: utf-8 -*

"""
树莓派外设驱动管理层
简单来说就是提供相对统一的调用方式，屏蔽调用GPIO等库的细节
例如：不需要关注某个外设是在哪个GPIO引脚
"""

import logging
from typing import List, TypeVar
from py_code.driver.Driver import Driver
from py_code.SingletonType import SingletonType
from atexit import register


@register
def atExit():
    logging.info(f"at exit注解生效，驱动管理器关闭驱动...")
    DriverManager().closeDrivers()


class DriverManager(metaclass=SingletonType):
    drivers: List[Driver] = []

    def __init__(self) -> None:
        pass

    def getDriver(self, driver: Driver, autoOpenDriver=True) -> Driver:
        """必须通过本方法来获取驱动实体"""
        if not (driver in self.drivers):
            self.drivers.append(driver)
        if autoOpenDriver:
            driver.openDriverIfClosed()
        return driver

    def closeDrivers(self):
        for driver in self.drivers:
            driver.closeDriverIfOpened()


def getDriver(driver: Driver) -> Driver:
    return DriverManager().getDriver(driver)
